package rensoft.android.presenter;

import java.io.File;
import java.io.IOException;

import static rensoft.java.lang.Lang.is;

import rensoft.android.HasActivity;
import rensoft.android.HasActivityPresenter;


import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.view.View;
import android.widget.ImageView;

public class StateImageViewPresenter extends HasActivityPresenter {

  private static final String IMAGE_FILE_PATH_STATE = "image_path_state";
  private final int viewId;
  private ImageView imageView;
  private File imagePath;

  public StateImageViewPresenter(HasActivity hasActivity, int viewId) {
    super(hasActivity);
    this.viewId = viewId;
  }

  public void clear() {
    imageView.setImageBitmap(null);
    imagePath = null;
  }

  @Override
  public void onCreateRestore(Bundle state) {
    super.onCreateRestore(state);
    String imageFilePath = state.getString(viewId + IMAGE_FILE_PATH_STATE);
    if (is(imageFilePath)) showImage(new File(imageFilePath));
  }

  @Override
  public void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);
    if (is(imagePath)) state.putString(viewId + IMAGE_FILE_PATH_STATE, imagePath.toString());
  }

  public void showImage(File imagePath) {
    this.imagePath = imagePath;
    try {
      Bitmap bitmap = Media.getBitmap(activity.getContentResolver(), Uri.fromFile(imagePath));
      imageView.setImageBitmap(bitmap);
      imageView.setVisibility(View.VISIBLE);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  protected void onCreate() {
    super.onCreate();
    imageView = getImageView(viewId);
  }
}
